"use client"
import React, { useEffect, useState } from 'react';
import { message, Form, Popconfirm, Typography, Table, InputNumber, Input, Button } from 'antd';

import { getUsers, updUser } from '@/api/usersApi'
import { carousel } from '@/utils/data.json'

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}: any) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
export default function Carousel() {
  const [form] = Form.useForm();
  const [data, setData] = useState(carousel);
  const [editingKey, setEditingKey] = useState('');
  const Init = async () => {
    const res = await getUsers()
    if (res?.flag) {
      setData(res.data)
    } else {
      message.error('服务器未响应');
    }
  }
  useEffect(() => {
    // Init()
  }, [])

  const isEditing = (record: any) => record.key === editingKey;

  const edit = (record: any) => {
    form.setFieldsValue({ name: '', age: '', address: '', ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields());

      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      render: (text: any, record: any, i: number) => {
        return i + 1;
      }
    },
    {
      title: '图片',
      dataIndex: 'url',
      width: '25%',
      render: (text: any, record: any) => {
        return (
          <img
            src={text}
            alt="图片"
            height='80px'
            style={{objectFit: 'cover' }}
          />
        );
      }
    },
    {
      title: '路径',
      dataIndex: 'url',
      width: '20%',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_: any, record: any) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginInlineEnd: 8 }}>
              <Button type="primary" size='small'>保存</Button>

            </Typography.Link>
            <Typography.Link onClick={() => setEditingKey('')} style={{ marginInlineEnd: 8 }}>
              <Button size='small'>取消</Button>

            </Typography.Link>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            <Button type="primary" size='small'>编辑</Button>
          </Typography.Link>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: { cell: EditableCell },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{ onChange: cancel }}
      />
    </Form>
  );
};
